import axios from "axios";
import { ElMessage } from "element-plus";
import { Base64 } from "js-base64";
import userUserStore from "@/store/modules/user.ts"
let request = axios.create({
    // baseURL:'/mock',
    baseURL:import.meta.env.VITE_APP_BASE_API,
    timeout:5000
})
// 加密token方法
function baseFun(){
    const token = localStorage.getItem('b0445-vue3-token');
    const base64 = Base64.encode(token+":")
    return "Basic "+base64
}
// 获取权限列表
const getMenus = ()=>{
    let userStore = userUserStore()
    const roleId = userStore.user?.role_id;
    const userMenus =userStore.user?.role?.menus;
    if(userStore.user?.username == "admin"){
        return
    }
    request({
        url:'/menus',
        method:'post',
        data:{
            roleId
        }
    }).then(response=>{
        const resp =response
        if(resp.status == 0){
            const menus = resp.data.menus
            if(userMenus?.length == menus.length){
                userMenus?.forEach(item =>{
                    if(menus.indexOf(item) === -1){
                        userStore.removeUser()
                        ElMessage({
                            message:"当前登录的用户权限被修改，请重新登录",
                            type:"warning"
                        })
                        window.location.href ="/login"
                    }
                })
            }else{
                userStore.removeUser()
                 ElMessage({
                            message:"当前登录的用户权限被修改，请重新登录",
                            type:"warning"
                        })
                        window.location.href ="/login"
            }
        }
        return
    })
}
// 请求拦截器
request.interceptors.request.use(
    function (config) {
    // 从本地获取token
    const token = localStorage.getItem('b0445-vue3-token');
    if(token){
        // 将加密之后的token设置到请求头当中
        config.headers.authorization=baseFun()
    }
    if(config.url !="/menus" && config.url !="/login"){
        getMenus()
    }
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 相应拦截器
request.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },  (error)=> {
    // 失败的回调。处理http网络错误信息
    let msg='';
    // http状态码
   let status=error.response.status;
   switch (status) {
    case 401:
        msg="token过期"
        break;
    case 403:
        msg="无权访问"
        break;
    case 404:
        msg="请求地址错误"
        break;
    case 500:
        msg="服务器出错"
        break;
   
    default:
       msg='无网络'
   }
   ElMessage({
    type:"error",
    message:msg
   })
   return Promise.reject(error);
  });
  export default request;